<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
	<title>Reference</title>
  <link rel="stylesheet" type="text/css" href="documentation.css" />
</head>
<body>

<h1 id="konstrukt-reference">Konstrukt Reference</h1>

<p><ul id="table-of-contents">
<li><a href="#konstrukt-reference">Konstrukt Reference</a><ul>
<li><a href="#component-essentials">Component essentials</a><ul>
<li><a href="#dispatch-life-cycle">Dispatch life-cycle</a></li>
<li><a href="#handlers">Handlers</a></li>
<li><a href="#dispatch">Dispatch</a></li>
<li><a href="#renderers">Renderers</a></li>
<li><a href="#subviews">Subviews</a></li>
<li><a href="#return-type">Return type</a></li>
<li><a href="#content-type-short-names">content-type short-names</a></li>
<li><a href="#input-handlers">Input handlers</a></li>
<li><a href="#wrappers">Wrappers</a></li>
<li><a href="#other-handlers">Other handlers</a></li>
</ul>
</li>
<li><a href="#http-input">HTTP input</a><ul>
<li><a href="#name-subtype-subspace">name, subtype, subspace</a></li>
<li><a href="#query-body">query, body</a></li>
<li><a href="#querystring-namespace">Querystring namespace</a></li>
<li><a href="#session">Session</a></li>
<li><a href="#cookies">Cookies</a></li>
<li><a href="#file-uploads">File uploads</a></li>
</ul>
</li>
<li><a href="#url-generation">Url generation</a><ul>
<li><a href="#urlstate-parameters">Urlstate parameters</a></li>
</ul>
</li>
<li><a href="#shared-objects">Shared objects</a><ul>
<li><a href="#identity">Identity</a></li>
<li><a href="#document">Document</a></li>
</ul>
</li>
<li><a href="#abnormal-responses">Abnormal responses</a><ul>
<li><a href="#untyped-responses">Untyped responses</a></li>
<li><a href="#meta-response">Meta response</a></li>
</ul>
</li>
<li><a href="#templates">Templates</a><ul>
<li><a href="#php-templates">PHP-templates</a></li>
</ul>
</li>
<li><a href="#component-creation">Component creation</a><ul>
<li><a href="#di-containers">DI containers</a></li>
<li><a href="#createcomponent">createComponent</a></li>
</ul>
</li>
<li><a href="#encoding">Encoding</a><ul>
<li><a href="#using-utf-8">Using utf-8</a></li>
<li><a href="#interfacing-with-legacy-applications-latin1">Interfacing with legacy applications (latin1)</a></li>
<li><a href="#charset-strategy">Charset strategy</a></li>
</ul>
</li>
<li><a href="#environment-setup">Environment/setup</a><ul>
<li><a href="#file-layout">File layout</a></li>
<li><a href="#static-content">Static content</a></li>
<li><a href="#global-handlers">Global handlers</a></li>
<li><a href="#naming-convention">Naming convention</a></li>
<li><a href="#bootstrap">Bootstrap</a></li>
</ul>
</li>
<li><a href="#debugging">Debugging</a><ul>
<li><a href="#logs">Logs</a></li>
<li><a href="#functional-testing">Functional testing</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</p>

<p>This document contains a description of the features of Konstrukt. For a more hands-on introduction, you should start out with <a href="getting-started-part1.html">getting started</a>.</p>

<p>There is also an autogenerated <a href="apidocs.html">api-reference</a>, which contains all classes, interfaces and methods in the library.</p>

<p>If you find any errors - even if it's just a spelling mistake, or a dodgy phrasing - don't hesitate to tell about it.</p>

<p>Troels Knak-Nielsen, January 2009, troelskn@gmail.com</p>

<h2 id="component-essentials">Component essentials</h2>

<p>A component is a class that extends from <code>k_Component</code>. Its purpose is to handle a request or delegate control to another component, that can handle it. This is much similar to how the Apache web server is structured. The way a component is addressed is through the URL path. Each path segment is mapped to a component. The special thing about Konstrukt in this respect, is that the exact mapping is determined at runtime. Each component is fully responsible for choosing the next component in the chain. This is a very powerful concept, but can also be slightly hard to comprehend at first. As a newcomer you may therefore find the <a href="#debugging">dispatch logging</a> useful.</p>

<h3 id="dispatch-life-cycle">Dispatch life-cycle</h3>

<p>A component is instantiated as an object before use. To allow for maximum flexibility in implementation, the constructor is not used for passing essential dependencies. These are instead passed immediately after creation through setters. Of these dependencies, the most important is the context, which will usually be another component instance.</p>

<p>As a developer you have great control over the creation of components. You can read more about this in the section on <a href="#component-creation">component creation</a>.</p>

<h3 id="handlers">Handlers</h3>

<p>Components can implement a number of fine grained methods to provide functionality. As a developer, you'll normally just implement/override a few of them, but if you need to, you can override them all, thereby hooking into the core workings of the framework. In particular, you will often implement renderers and input handlers, as well as <code>map()</code> and in some cases <code>dispatch()</code>. If you find your self overriding any of <code>execute()</code>, <code>render()</code>, <code>GET()</code>, <code>POST()</code>, <code>PUT()</code> or <code>wrap()</code>, it should be a warning sign that you are doing some thing wrong; These all default to delegate control to more specific handlers and as such you usually wouldn't have to override them.</p>

<h3 id="dispatch">Dispatch</h3>

<p>Once the component is instantiated, the context will delegate control to the component, by invoking its <code>dispatch()</code> method. <code>dispatch()</code> inspects the remainder of the path (the <code>subspace</code>) and does one of two things: If the path contains any further names, it will call <code>map()</code> with the next name, and receive a corresponding classname. It will then instantiate this component, becoming the context, and dispatch to it. If there is no further names (it is the final component), it will handle the request.</p>

<p>While you can hook in to various places in the request handling, the most common is to implement a <a href="#renderers">renderer</a> - typically <code>renderHtml()</code>. Since you're application will presumably contain more than one component, you will also get acquainted with the <code>map()</code> method.</p>

<p>Some times, a request can contain a <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3">message-body</a> - The typical case being a POST'ed web-form. To handle this, you'd implement an input handler <code>postForm()</code>.</p>

<p>The already mentioned <code>dispatch()</code> method can be overridden to put code that should execute for all types of requests to the component. It is typically used for access-control/authentication and for checking the existence of the resource (throw a <code>k_PageNotFound</code> if not). If you override this (or other) handler(s), remember to call the parent implementation at the end. Eg.:</p>

<pre class="php"><span class="kw2">class</span> MyComponent <span class="kw2">extends</span> k_Component <span class="br0">&#123;</span>
  <span class="kw2">function</span> dispatch<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw1">if</span> <span class="br0">&#40;</span>!<span class="re0">$this</span>-&gt;<span class="me1">model</span>-&gt;<span class="me1">find</span><span class="br0">&#40;</span><span class="re0">$this</span>-&gt;<span class="me1">name</span><span class="br0">&#41;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
      <span class="kw1">throw</span> <span class="kw2">new</span> k_PageNotFound<span class="br0">&#40;</span><span class="br0">&#41;</span>;
    <span class="br0">&#125;</span>
    <span class="kw1">return</span> <span class="kw2">parent</span>::<span class="me2">dispatch</span><span class="br0">&#40;</span><span class="br0">&#41;</span>;
  <span class="br0">&#125;</span>
<span class="br0">&#125;</span></pre>

<p>Some times, a request can contain a payload (Known as the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3">message-body</a>). This is only allowed with POST and PUT types requests - the typical use-case being a <code>&lt;form&gt;</code> being submitted through POST. To handle this, you will have to implement a handler matching the request-type and the content-type of the request. For example, to handle a regular form, you would implement <code>postForm()</code>. Another, slighty less common, handler would be <code>postMultipart()</code>, which would be used if the form contains <a href="#file-uploads">file uploads</a>. You can read more under the section <a href="#input-handlers">input handlers</a>.</p>

<h3 id="renderers">Renderers</h3>

<p>Most components have a way to render themselves. When a regular GET request is issued to the component, it will try to render it by calling a so-called <em>renderer</em>. Renderers are simply methods that are prefixed with <code>render</code> and followed by a short-name corresponding to the content-type that they provide. For the majority, <code>renderHtml()</code> is the most common renderer, but you can implement other content-types such as <code>renderJson()</code> or <code>renderRss()</code>. If a component provides multiple renderers, it will pick one based on the <code>Accept</code> header of the incoming request. This means that the client (usually a browser) can decide which format it prefers. This is a feature known as <em>content-type negotiation</em>, because it happens automatically based on the clients preferences and the available formats.</p>

<p>Some times you may need to have a URL refer directly to a specific representation (content-type) of a component - In this case, you can postfix the URL with the content-type short-name. For example, the URL <code>/foo/bar</code> is subject to content-negotiation, while <code>/foo/bar.csv</code> will only render through <code>renderCsv()</code> (Of course provided that this method is implemented).</p>

<h3 id="subviews">Subviews</h3>

<p>Some times you need to be able to display alternative views of the same resource + content-type. The most common example is for forms. A url like <code>/superheroes/batman</code> might show a html page for the dark knight, but which url should be used to edit the stats for him? One option is to use a sub component, as in <code>/superheroes/batman/edit</code>, but this suggests that <code>edit</code> is a resource under <code>batmna</code>, when it is really just another representation of it. A place where this causes trouble, is if a component has children. For example, <code>/superheroes/create</code> might be a form for creating a new entity, but it could also refer to an entity named <code>create</code>.</p>

<p>To deal with these issues, Konstrukt provides a concept called <em>subviews</em>. If the url contains a parameter without any value, following right after the question mark, it will be used as a prefix to the render method. For example, <code>/foo/bar.html?edit</code> will resolve to <code>renderHtmlEdit</code>, if defined. Again, the content-type may be left out, so that <code>/foo/bar?edit</code> resolves to the same handler.</p>

<p>To have a subview, there <em>must</em> be a primary view. Eg. you can't have <code>renderHtmlEdit</code> without having <code>renderHtml</code>.</p>

<p>Note that the subview parameter is also a query-string parameter, so it will turn up in <code>query()</code>.</p>

<h3 id="return-type">Return type</h3>

<p>The return type of a renderer depends on the content-type it handles. It is always valid to return an instance of <code>k_Response</code>, but most of the time you should just return a language primitive (such as a string for <code>renderHtml()</code>) and it will be wrapped in an appropriately typed response instance. The primitive type to return depends on the content-type. This type is also called the internal type, and it is the same type that will be passed to any <a href="#wrappers">wrappers</a>. The supported internal types can be read from this chart:</p>

<table>
<thead>
<tr>
  <th>content-type</th>
  <th>short name</th>
  <th>internal type(s)</th>
</tr>
</thead>
<tbody>
<tr>
  <td>text/html</td>
  <td>html</td>
  <td>string</td>
</tr>
<tr>
  <td>text/plain</td>
  <td>text</td>
  <td>string</td>
</tr>
<tr>
  <td>application/json</td>
  <td>json</td>
  <td>any scalar, array</td>
</tr>
<tr>
  <td>application/x-serialized-php</td>
  <td>php</td>
  <td>anything that can be serialized</td>
</tr>
<tr>
  <td>text/xml</td>
  <td>xml</td>
  <td>string, DomNode, SimpleXMLElement</td>
</tr>
</tbody>
</table>

<p>Other HTTP-methods than GET may also render an output. To do so, you can call <code>render()</code> from within the handler, and it will then delegate to the appropriate render-method. (This is what <code>GET()</code> does behind the scenes). For example, you might end your <code>postForm()</code> method with the line:</p>

<pre class="php"><span class="kw1">return</span> <span class="re0">$this</span>-&gt;<span class="me1">render</span><span class="br0">&#40;</span><span class="br0">&#41;</span>;</pre>

<p class="note">Note: The content-type of renderers is based on the <code>Accept</code> header of the request, and defines the type of response that goes out. Certain requests (notably POST and PUT) may have a different content-type, specifying the type of the message-body. This is handled by a related, but different mechanism called <a href="#input-handlers">Content-Type delegation</a></p>

<h3 id="content-type-short-names">content-type short-names</h3>

<p>There are various places where content-types are referred to through their short-names. For example, <a href="#renderers">renderers</a> are named according to the content-type they provide. So are <a href="#input-handlers">input handlers</a>. There are many content-types, but the most used ones are depicted in the table below:</p>

<table>
<thead>
<tr>
  <th>content-type</th>
  <th>short name</th>
  <th>render method</th>
</tr>
</thead>
<tbody>
<tr>
  <td>text/html</td>
  <td>html</td>
  <td>renderHtml</td>
</tr>
<tr>
  <td>text/xml</td>
  <td>xml</td>
  <td>renderXml</td>
</tr>
<tr>
  <td>text/plain</td>
  <td>text</td>
  <td>renderText</td>
</tr>
<tr>
  <td>text/csv</td>
  <td>csv</td>
  <td>renderCsv</td>
</tr>
<tr>
  <td>text/x-vcard</td>
  <td>vcard</td>
  <td>renderVcard</td>
</tr>
<tr>
  <td>application/atom+xml</td>
  <td>atom</td>
  <td>renderAtom</td>
</tr>
<tr>
  <td>application/calendar+xml</td>
  <td>xcal</td>
  <td>renderXCal</td>
</tr>
<tr>
  <td>application/rdf+xml</td>
  <td>rdf</td>
  <td>renderRdf</td>
</tr>
<tr>
  <td>application/json</td>
  <td>json</td>
  <td>renderJson</td>
</tr>
<tr>
  <td>application/pdf</td>
  <td>pdf</td>
  <td>renderPdf</td>
</tr>
<tr>
  <td>image/svg+xml</td>
  <td>svg</td>
  <td>renderSvg</td>
</tr>
</tbody>
</table>

<p>You can add your own content-types to the global array <code>$GLOBALS['konstrukt_content_types']</code> as follows:</p>

<pre class="php"><span class="re0">$GLOBALS</span><span class="br0">&#91;</span><span class="st0">'konstrukt_content_types'</span><span class="br0">&#93;</span><span class="br0">&#91;</span><span class="st0">'test/html'</span><span class="br0">&#93;</span> = <span class="st0">'html'</span>;</pre>

<p>If you're adding a generic content-type, you might want mention it to the developers, and we'll try to incorporate it in the main library.</p>

<h3 id="input-handlers">Input handlers</h3>

<p>The HTTP-methods POST and PUT are special in that they contain a message-body. The content-type of this payload is specified in the requests Content-Type header.. To distinguish between them, the default implementation of <code>POST()</code> and <code>PUT()</code> will try to dispatch to a handler corresponding to the requests content-type. For example, a regular posted form has the <code>application/x-www-form-urlencoded</code> content-type. This will be delegated to <code>postForm()</code>. A request of the type <code>application/json</code> will be delegated to <code>postJson()</code>. This feature, which is known as <em>content-type delegation</em>, allows you to implement support for different content-types in a standard fashion.</p>

<p>The naming of the content-type handlers corresponds to their <a href="#content-type-short-names">short-names</a>, but the most commonly used are depicted below:</p>

<table>
<thead>
<tr>
  <th>content-type</th>
  <th>POST handler</th>
  <th>PUT handler</th>
</tr>
</thead>
<tbody>
<tr>
  <td>application/x-www-form-urlencoded</td>
  <td>postForm</td>
  <td>putForm</td>
</tr>
<tr>
  <td>multipart/form-data</td>
  <td>postMultipart</td>
  <td>putMultipart</td>
</tr>
<tr>
  <td>application/json</td>
  <td>postJson</td>
  <td>putJson</td>
</tr>
</tbody>
</table>

<p>This mechanism is somewhat similar to <a href="#renderers">content-type negotiation</a>, but differs in that <code>render()</code> relates to the <code>Accept</code> header - Which has to do with the output-format of the HTTP-response - while content-type delegation relates to the <code>Content-Type</code> header - which has to do with the input-format of the HTTP-request.</p>

<h3 id="wrappers">Wrappers</h3>

<p>When a component delegates control to a sub-component, it can some times be useful to decorate the response. A typical case is to render navigation or to render the <code>&lt;head&gt;</code> tags in the root component. While you could manually override <code>dispatch()</code> or <code>forward()</code> to do this, there is already a mechanism in Konstrukt called <em>wrappers</em>. Wrappers are typed just like <a href="#renderers">renderers</a> and they are picked according to the content-type of the sub-components response. This means that <code>wrapHtml()</code> will only apply to sub-components that return a html-response. There is a special hook for intercepting un-typed (<code>k_HttpResponse</code>) responses, which is <code>renderHttp()</code>. It is rarely used, but if you need it, it's there.</p>

<p>A wrapper takes a single argument, which is the internal representation of the response to be wrapped. Like the renderers, wrappers can either return an instance of <code>k_Response</code> or just return the internal preresentation, which will then be converted to a typed response automatically.</p>

<h3 id="other-handlers">Other handlers</h3>

<p>As already mentioned, there are a few other handlers which can be implemented in your components. If you want to support all the major HTTP verbs (HEAD, PUT, DELETE), you can do so by implementing the correct handler. For handling HEAD and DELETE, simply implement a method named <code>HEAD()</code> and <code>DELETE()</code> respectively. The PUT method follows the pattern of POST, so you shouldn't implement <code>PUT()</code>, but rather a handler specific to the input type; Eg. <code>putForm</code> or <code>putJson</code> etc.</p>

<h2 id="http-input">HTTP input</h2>

<p>A component can access the various inputs that comes from a http-request. These are obtained through the <code>$context</code> object, rather than through a global place, which makes components very encapsulated and - among other things - more testable.</p>

<p>Note that all these properties are accessed through methods, not as fields. So you would refer to <code>$this-&gt;name()</code> rather than <code>$this-&gt;name</code></p>

<h3 id="name-subtype-subspace">name, subtype, subspace</h3>

<p>Initially the most important input is probably the <code>name</code>. This returns the part of the url that this component belongs to. For the last component of the url <code>/foo/bar/quux</code>, the name would be <code>quux</code>. This property is often used as a primary key for identifying the underlying resource.</p>

<p>The <code>subtype</code> property is the part of a path-segment that comes after the name, delimited by a dot. It's used internally to identify the content-type. As a developer you'll probably not need to access this very often.</p>

<p>The <code>subspace</code> property contains the remaining part of the path, for a component that isn't the last in the dispatch chain. For example, given the component identified as <code>bar</code> in the url <code>/foo/bar/quux</code>, the subspace would be <code>quux</code>. This property is also rarely used directly.</p>

<h3 id="query-body">query, body</h3>

<p>In addition to the url/path, there are two important input sources; The query-string and the request body. In plain PHP, these are available through <code>$_GET</code> and <code>$_POST</code> respectively, but in Konstrukt they are accessed through <code>query()</code> and <code>body()</code>. This naming is more precise, in that query-string parameters aren't just for GET requests, and a request body can come with other kinds of requests than a POST.</p>

<p>You can call the accessors without any arguments and get a hashmap back, or you can provide a name, and just get the value for that field. If the key isn't set, you will get back <code>null</code>, rather than a warning.</p>

<pre class="php">  <span class="re0">$this</span>-&gt;<span class="me1">query</span><span class="br0">&#40;</span><span class="br0">&#41;</span>; <span class="co1">// array('foo' =&gt; 'bar')</span>
  <span class="re0">$this</span>-&gt;<span class="me1">query</span><span class="br0">&#40;</span><span class="st0">'foo'</span><span class="br0">&#41;</span>; <span class="co1">// 'bar'</span></pre>

<p>You can also pass a default value that will be returned if the specified key doesn't exist.</p>

<pre class="php">  <span class="co1">// /baz?grault=waldo</span>
  <span class="re0">$this</span>-&gt;<span class="me1">query</span><span class="br0">&#40;</span><span class="st0">'foo'</span>, <span class="st0">'bar'</span><span class="br0">&#41;</span>; <span class="co1">// 'bar'</span></pre>

<p>The renderer operates with the concept of <em>subview</em>. This is simply a query-string parameter without any value. In a url like <code>/foo/bar?quux</code>, the subview would be <code>quux</code>. This property is used to determine the appropriate <a href="#renderers">renderer</a>. While the value could occur anywhere in the query-string, it is usually placed as the first element, right after the question mark.</p>

<h3 id="querystring-namespace">Querystring namespace</h3>

<p>Because the querystring is shared amongst every component, you can sometimes run into problems when you need to pass parameters to multiple components (Not exactly a common requirement, but it can happen). Components can use a namespace to protect the querystring in these cases.
It's the context that specifies a namespace for its subcomponents, and it works completely transparent to the subcomponent. To create a component with a namespace, your <code>map()</code> method should return an array instead of a string, where the first element is the namespace and the second is the classname.</p>

<h3 id="session">Session</h3>

<p>Sessions are a very powerful feature for maintaining state in a web application. Unfortunately it's often overused. While there are cases where it's the best pick, you should generally try to use some other means of maintaining state, if at all possible. That said, Konstrukt provides access to PHPs session mechanism, through a wrapper.</p>

<p>Each component has a method <code>session()</code> that can be called in two ways. Either you provide an argument (Which should be a string), and you'll get the value of a session variable by that name back (or null, if it's not defined). Alternatively you can call it without any arguments, in which case you'll an object back of the type <code>k_adapter_SessionAccess</code>. It has methods for getting/setting session variables and other session-related functions.</p>

<p>Note that you don't need to worry about calling <code>session_start()</code>, since this is done automatically by the wrapper.</p>

<h3 id="cookies">Cookies</h3>

<p>A cookie is a mixed client/server side way of maintaining state. It has a number of limitations which makes it a less popular choice, but it can still be useful in certain cases. You can access cookies through a wrapper in Konstrukt.</p>

<p>The cookie wrapper works just as the session wrapper. Each component has a method <code>cookie()</code> that can be called with a parameter to retrieve the value of a cookie by that name, or without any arguments to get an object back of the type <code>k_adapter_CookieAccess</code>.</p>

<h3 id="file-uploads">File uploads</h3>

<p>In PHP files uploaded with a form are accessible through <code>$_FILES</code>. Inside a component, you can access the same information through the method <code>file()</code>. You can either pass a parameter to get back a specific file or call it without any arguments to get a hashmap of all files. A file is wrapped in an object of the type <code>k_adapter_UploadedFile</code>, which helps to abstract direct access to the filesystem away. As a side effect it also has a simpler interface than PHPs native handling of file uploads. To save an uploaded file, just call <code>writeTo($path_destination)</code> with the destination as argument.</p>

<p>Note that you need to go through the <a href="http://www.php.net/features.file-upload.post-method.php">regular hoops to get file uploads working</a>. Most importantly you need to set the <code>enctype="multipart/form-data"</code> property on your form tag. When you do this, the hanler for processing the form will be named <code>postMultipart()</code>. (See <a href="#input-handlers">input handlers</a> for more details).</p>

<h2 id="url-generation">Url generation</h2>

<p>All components are tightly coupled to a url. Components can parse (dispatch) urls, and they can also generate urls. To make your application as flexible as possible, it is recommended that you generate internal urls, using the <code>url()</code> method, rather than hardcoding them as strings. From within a component, you can call <code>url()</code> without any parameters to get a url pointing to the current component. As the first argument, you can pass a subspace, and as the second argument, you can pass a hash of query-string parameters. Eg.:</p>

<pre class="php">   <span class="re0">$this</span>-&gt;<span class="me1">url</span><span class="br0">&#40;</span><span class="st0">'foo'</span>, <span class="kw3">array</span><span class="br0">&#40;</span><span class="st0">'bar'</span> =&gt; <span class="nu0">42</span><span class="br0">&#41;</span><span class="br0">&#41;</span>; <span class="co1">// -&gt; /url/for/this/component/foo?bar=42</span></pre>

<p>Generating urls this way, makes it easy to move components around without having to make any changes to the view.</p>

<p>Note that the first argument isn't automatically encoded. You can optionally pass an array of strings instead. These are then encoded and joined with a path-separator (A slash). Eg.:</p>

<pre class="php">   <span class="re0">$this</span>-&gt;<span class="me1">url</span><span class="br0">&#40;</span><span class="kw3">array</span><span class="br0">&#40;</span><span class="st0">'foo'</span>, <span class="st0">'quux'</span><span class="br0">&#41;</span>, <span class="kw3">array</span><span class="br0">&#40;</span><span class="st0">'bar'</span> =&gt; <span class="nu0">42</span><span class="br0">&#41;</span><span class="br0">&#41;</span>; <span class="co1">// -&gt; /url/for/this/component/foo/quux?bar=42</span></pre>

<p class="note">Note:   Apache has a <a href="http://httpd.apache.org/docs/2.2/mod/core.html#allowencodedslashes">security feature</a> that disallows url path segments to contain an encoded slash. Thus, you should avoid names that contains slashes. In general, it is a good idea to stick to <code>a-z0-9_-</code> for url names.</p>

<h3 id="urlstate-parameters">Urlstate parameters</h3>

<p>If a component needs to maintain view-related state, you have a limited set of options. In essence, the choice is between propagating state over urls (client side state) or using a server side mechanism (eg. sessions). Cookies are also a solution, but it has most of the problems associated with session state, and even some of its own. Client side state is often the superior choice, but it is tedious to do by hand. Konstrukt has therefore a mechanism builtin to support this. Viewstate can be propagated as querystring parameters, using the <code>urlstate</code> property of a component. Properties that are set on the urlstate will be automatically set on any urls for the component, unless explicitly overridden. A typical usecase is for searches and other data-views.</p>

<p>Urlstate parameters are specified, along with their initial value, by implementing the <code>url_init</code> in your component. For example, to the following specifies a single parameter "foo". If no input is present for it, it has the value "bar":</p>

<pre class="php"><span class="kw2">class</span> MyStatefulComponent <span class="kw2">extends</span> k_Component <span class="br0">&#123;</span>
  <span class="kw2">protected</span> <span class="re0">$url_init</span> = <span class="kw3">array</span><span class="br0">&#40;</span><span class="st0">'foo'</span> =&gt; <span class="st0">&quot;bar&quot;</span><span class="br0">&#41;</span>;
<span class="br0">&#125;</span></pre>

<p>If a urlstate parameter is passed on the querystring, it will automatically override the urlstate containers value. Eg. for a request with the query-string <code>?foo=quux</code>, the following would yield "quux":</p>

<pre class="php">  <span class="re0">$this</span>-&gt;<span class="me1">url_state</span>-&gt;<span class="me1">get</span><span class="br0">&#40;</span><span class="st0">'foo'</span><span class="br0">&#41;</span>; <span class="co1">// -&gt; &quot;quux&quot;</span></pre>

<h2 id="shared-objects">Shared objects</h2>

<p>A few objects are shared amongst all components.</p>

<h3 id="identity">Identity</h3>

<p>The identity object is an object represeting the current user. Every component can access the identity by calling the access <code>identity()</code>. The default implementation is <code>k_Anonymous</code>.</p>

<p>The identity is loaded from an <code>k_DefaultIdentityLoader</code>, that can be configured with the <a href="#bootstrap">bootstrap</a>. An identity-loader is a simple factory, that gets passed the top-level context, and is expected to return an instance of <code>k_Identity</code>. The usual use case is to load a user-object from the database or an authentication system.</p>

<h3 id="document">Document</h3>

<p>The document is an instance of <code>k_Document</code>, and contains values that are global to the HTML document, such as title, CSS includes etc. A component can access the document via the <code>document()</code> method.</p>

<p>The default document has accessors for setting the title, adding external javascript and Css files to <code>&lt;head&gt;</code>, and adding javascript code to run on page load. This is a fairly limited number of properties. If you need more, you could subclass <code>k_Document</code> and set your own implementation in the <a href="#bootstrap">bootstrap</a>. It is recommended to keep such properties as specific as possible, to prevent that the object becomes a dumping ground for global variables.</p>

<h2 id="abnormal-responses">Abnormal responses</h2>

<h3 id="untyped-responses">Untyped responses</h3>

<p>By default, components are expected to return either an instance of <code>k_Response</code> or an internal type, that is then converted. While you would usually want to return a response that matches the expected type (Eg. a <code>k_HtmlResponse</code> from <code>renderHttp()</code> etc.), you can return other types. A common reason to use this, is to respond with a redirect.</p>

<p>There are three specialised responses (all types of <code>k_Response</code>) that should be used for redirects:</p>

<dl>
<dt><code>k_MovedPermanently</code></dt>
<dd>Use this if the URL has changed (Eg. a page has been renamed).</dd>

<dt><code>k_SeeOther</code></dt>
<dd>Use this type of redirect specifically for redirecting after POST.</dd>

<dt><code>k_TemporaryRedirect</code></dt>
<dd>Use this type of redirect if the destination changes from request to request, or if you want the client to keep using the requested URI in the future.</dd>
</dl>

<p>These all take the target URL as argument for the constructor.</p>

<h3 id="meta-response">Meta response</h3>

<p>A meta response is not really a response. It is a type of exception, that can be caught at the top-level dispatcher and there turned into a component. Other frameworks deal with this through internal redirects, and you could think of it as such. You should use meta responses for a number of specific error-states that can occur in your application.</p>

<p>While you could just return a http response, the meta response adds a level of indirection that can be useful at a later point. The primary benefit of using a meta response over a http response, is that it gives you control over rendering of various error-pages. For example, rather than constructing a http response with status 404, you should use the meta response <code>k_PageNotFound</code>. This makes it possible to have a customised page for all "not found" responses.</p>

<p>The currently supported metaresponses are:</p>

<dl>
<dt><code>k_Forbidden</code></dt>
<dd>Raise this if the user doesn't have access to the requested resource.</dd>

<dt><code>k_PageNotFound</code></dt>
<dd>Raise this if the requested resource couldn't be found.</dd>

<dt><code>k_MethodNotAllowed</code></dt>
<dd>Raise this if resource doesn't support the requested HTTP method.</dd>

<dt><code>k_NotImplemented</code></dt>
<dd>This is roughly the HTTP equivalent to a "todo"</dd>
</dl>

<p>A meta response is associated with a component class name. For example, <code>k_Forbidden</code> resolves to <code>k_DefaultForbiddenComponent</code>. To get a customised handler for these types of responses, you can let your <a href="#component-creation">component creator</a> return a custom component instead of the defaults.</p>

<h2 id="templates">Templates</h2>

<p>Components usually return a html string. How they are rendered is largely left up to the developer. A common practise is to use a template engine though. Konstrukt includes a very simple template engine, which just wraps a regular PHP script in an output buffer. This strategy of using PHP as a template language works fine as long as you have some control over the provider of templates. It does have some drawbacks though, so some people might prefer to use a real template engine. Konstrukt comes with an example of how to use the Smarty template engine, but it should be equally simple to use any other template engine.</p>

<h3 id="php-templates">PHP-templates</h3>

<p>To use the default template engine, you should instantiate and object of <code>k_Template</code>. The interface is simple; You pass a path to a PHP template. Calling <code>render()</code> will include the file inside a buffer and return the output. The calling component must pass a reference to itself to the template. This is to allow the template to access variables it might need. You should add methods on your component to provide the variables that your template might need.</p>

<p>The template binds a few global functions to make it easier for the template to call certain common features with a simple syntax. These are:</p>

<dl>
<dt><code>e()</code></dt>
<dd>This function escapes HTML special-characters in input and prints it in-place. Use this for embedding values in html-documents.</dd>

<dt><code>__()</code>, <code>t()</code></dt>
<dd>These are both aliases for <code>$context-&gt;__()</code>. You can use this hook for implementing i18n support in your application. Note that there is no default implementation for <code>__()</code>, so you need to explicitly implement this in your components, if you wish to support the feature.</dd>

<dt><code>url()</code></dt>
<dd>This is bound to <code>$context-&gt;url()</code>.</dd>
</dl>

<h2 id="component-creation">Component creation</h2>

<p>In the <a href="#dispatch-map-forward">dispatch process</a>, a component may delegate control to a sub component. In doing so, the new component must be instantiated first. This task is handled by a discrete object, called a <em>component creator</em>. This can be configured in the <a href="#bootstrap">bootstrap</a>, which allows you to replace this without having to mingle with the internals of the library.</p>

<h3 id="di-containers">DI containers</h3>

<p>The intended use for a component creator, is to allow the use of a <a href="http://c2.com/cgi/wiki?DependencyInjection">dependency injection container</a> for creation of components. The base class for components (<code>k_Component</code>) doesn't have a constructor defined, which allows you free control over this for your components. This is practical because DI containers often use the constructor to provide dependencies. By default, Konstrukt doesn't provide a DI container, but it comes with bindings for <a href="https://phemto.svn.sourceforge.net/svnroot/phemto/trunk">Phemto</a>, and it's very simple to write adapters for other containers.</p>

<h3 id="createcomponent">createComponent</h3>

<p>Most sub components are created from the dispatch process, but sometimes you need to create components manually. To do this, you can invoke the <code>createComponent()</code> method on a component, which would create a new sub component. The method takes an optional namespace, which is the <a href="#querystring-namespace">namespace used for querystring parameters</a>.</p>

<h2 id="encoding">Encoding</h2>

<p>Until version 6 becomes current, PHP is stuck with a primitive view of string data, where strings are treated as bytestreams. Many libraries, extensions and even core functionality in PHP, assumes that strings are single-byte streams. This means that each byte is interpreted as a character, the consequence being that only 256 different characters can be represented. Furthermore, the default charset assumed is ISO-8859-1 (also known as latin1). As long as we only want to represent western European texts this suffices, but in our multi cultural world, this is inadequate.</p>

<h3 id="using-utf-8">Using utf-8</h3>

<p>Even if your main audience is English speaking, your users may still have foreign names, that can't be written with the limited charset of latin1. In addition, there are a number of <a href="http://en.wikipedia.org/wiki/ISO/IEC_8859-1#ISO-8859-1_and_Windows-1252_confusion">ambiguities with regards to the latin1 standard</a>, meaning that you can end up with corrupt data, even if you do things by the book. Currently, the best solution is therefore to use UTF-8 as encoding throughout your application. This strategy does have its pitfalls, but so does using latin1. It is important to get these things right from the beginning, since it's a thing that is very hard to change later.</p>

<p>Konstrukt distinguishes between the charset that it speaks on the HTTP level (The charset that the client sees) and the internal charset. By default, it will use UTF-8 in both places, but you can change the outside charset by a simple configuration option. Internally, you must use UTF-8. If you use a database, you should make sure that data is stored as UTF-8 or another Unicode capable encoding, and you should also make sure that the connection between PHP and database is set to UTF-8 (This only apply to some databases, such as MySql). Also, make sure that any files - especially template files - are saved as UTF-8 (Without BOM). This covers the most common problems with UTF-8.</p>

<p>There is a good overview of the core PHP functions, that needs special treatment to work with UTF-8 at <a href="http://www.phpwact.org/php/i18n/utf-8">http://www.phpwact.org/php/i18n/utf-8</a>.</p>

<h3 id="interfacing-with-legacy-applications-latin1">Interfacing with legacy applications (latin1)</h3>

<p>If you're interfacing with code that speaks iso-8859-1, you will have to manually convert to utf-8. You can do this on by simply running the output from your <a href="#renderers">renderers</a> through the function <code>utf8_encode</code>. Additionally you will need to decode any input data (<code>query()</code>, <code>body()</code>, <code>name()</code> etc.) as these are internally represented as utf-8, regardless of the internal charset. If you follow these two guidelines, your code should fit nicely in to the framework. Of course, you are encouraged to upgrade to use UTF-8, since it will not only make things easier, but it will also eliminate a number of bugs and limitations.</p>

<h3 id="charset-strategy">Charset strategy</h3>

<p>To change the charset strategy (The charset that the application presents itself in), assign a <code>k_charset_CharsetStrategy</code> in the <a href="#bootstrap">bootstrap</a>, using <code>setCharsetStrategy()</code>. Konstrukt comes with the following options:</p>

<dl>
<dt><code>k_charset_Utf8CharsetStrategy</code></dt>
<dd>The default choice. Encodes the response as UTF-8, and interprets the input as UTF-8.</dd>

<dt><code>k_charset_Latin1CharsetStrategy</code></dt>
<dd>Legacy compatibility. Encodes the response as ISO-8859-1, and interprets the input as ISO-8859-1.</dd>
</dl>

<p>It is strongly recommended that you keep the default (UTF-8) strategy.</p>

<h2 id="environment-setup">Environment/setup</h2>

<p>Konstrukt is fairly liberal about how files are organised. The library must of course be included in your application (Eg. <code>lib/konstrukt.inc.php</code>).</p>

<p>To make it easier to get started with Konstrukt, a "starterpack" is included, that gives you a default directory layout and configuration. If you're starting a new project, it's probably a good idea to follow this standard. However, these are just suggestions and it shouldn't be a problem to divert from it.</p>

<p>Currently, Konstrukt comes with two different variations of the starterpack. They are quite similar, where one is a subset of the other. <code>starterpack_light</code> doesn't have any external dependencies, except for Konstrukt. It doesn't feature a DI container and it uses the simple PHP-style templates that is provided through <code>k_Template</code>. The other option - <code>starterpack_default</code> adds Phemto as a DI container and the Smarty template engine. It also gives you a place to put test cases, using SimpleTest. This is the default recommended setup; If you don't want to use one of the components, you may find it easier to remove from the default package, rather than adding to the light package.</p>

<h3 id="file-layout">File layout</h3>

<p>The file layout of the starterpacks are as follows:</p>

<pre><code>config/               -- Global settings and other static configuration files
lib/                  -- Application specific PHP-code
lib/components/       -- Subclasses of k_Component.
log/                  -- Folder for various logfiles
log/development.log   -- The application debug log.
log/error.log         -- PHP error-log.
templates/            -- Template files
templates_c/          -- Compiled Smarty template files. This is specific for `starterpack_default`
test/                 -- Automated tests. This is specific for `starterpack_default`
test/unit/            -- Unit tests.
test/functional/      -- Functional tests (Eg. tests of individual components).
var/                  -- Place for various datafiles, such as sqlite database etc.
www/                  -- The directory that should be mounted as web root. Contains static content, such as Javascript files.
www/.htaccess         -- Contains configuration for Apache.
</code></pre>

<h3 id="static-content">Static content</h3>

<p>The <code>www</code> folder should be mounted as the <code>DocumentRoot</code> of your website. <code>mod_rewrite</code> is used to delegate control to Konstrukt. You can place static content in this folder, such as Javascript and CSS files or other static content. Apache will then serve these directly, without invoking PHP.</p>

<p>This setup assumes that <code>www</code> is mounted as the web root. If you want to run your application from a subfolder, you will have to specify the <code>href_base</code> to your <a href="#bootstrap">bootstrap</a>. In <code>www/index.php</code>, call <code>setHrefBase()</code> with the relative location to the web root.</p>

<h3 id="global-handlers">Global handlers</h3>

<p>Konstrukt comes with a default error handler and a class loader - <code>k_exceptions_error_handler</code> and <code>k_autoload</code>.</p>

<p>The error handler simply converts all errors into exceptions. It's recommended that you develop with this configuration, since it will force you to deal with errors, rather than ignoring them.</p>

<p>The class loader uses a simple convention to try and autoload undefined classes; Classnames are lowercased and underscores replaced with directory-separators. So a class named <code>foo_Bar</code> is expected to be defined in <code>foo/bar.php</code>. This convention is similar to  that of PEAR and Zend Framework, except that file/directory names are all lowercased. The reason for this is that classnames are case insensitive in PHP, while filenames aren't (At least not on unix systems).</p>

<h3 id="naming-convention">Naming convention</h3>

<p>If you use the default autoloader (<code>k_autoload</code>), you should place your components in <code>/lib/components/</code> and name them accordingly. Eg. The following component should be placed in the file <code>/lib/components/foo/bar.php</code> :</p>

<pre class="php"><span class="kw2">class</span> components_foo_Bar <span class="kw2">extends</span> k_Component <span class="br0">&#123;</span>
  ...
<span class="br0">&#125;</span></pre>

<h3 id="bootstrap">Bootstrap</h3>

<p>The bootstrap is an object that is used to create the root component and dispatch it. It's really just a factory, that makes it simpler to configure the application.</p>

<p>To start your application, create a default bootstrap using the <code>k()</code> function. This will return an instance of <code>k_Bootstrap</code>. The bootstrap has a number of default settings which you can override. Finally, the bootstrap can invoke the application, by calling the method <code>run()</code>. Each setter-method returns <code>$this</code>, allowing you to write in a fluent style.</p>

<p>The most important setters on the bootstrap are:</p>

<dl>
<dt><code>setComponentCreator</code></dt>
<dd>Sets the <a href="#component-creation">componentcreator</a> to use.</dd>

<dt><code>setCharsetStrategy</code></dt>
<dd>Set the <a href="#encoding">charsetstrategy</a>.</dd>

<dt><code>setDebug</code></dt>
<dd>Enable/disable the in-browser <a href="#debugging">debug-bar</a>.</dd>

<dt><code>setLog</code></dt>
<dd>Specifies a filename to log <a href="#debugging">debug information to</a>.</dd>

<dt><code>setHrefBase</code></dt>
<dd>Sets the base href, if the application isn't <a href="#static-content">mounted at the web root</a>.</dd>
</dl>

<h2 id="debugging">Debugging</h2>

<p>Konstrukt comes with some tools for making development easier. Since the dispatch process of components isn't as simple as plain php or a front controller setup, it can be useful to see the exact chain of events, to figure out which component is responsible for rendering the output. To this end, the dispatch is logged. You can get debug output in two ways; Through the debug-bar or through the logfile. For a production site, you can disable debugging to improve performance.</p>

<p>You can enable/disable debugging with the relevant methods of the bootstrap.</p>

<p>In addition to dispatch logging, you can also send arbitrary information to the logger. Each component has a protected method <code>debug()</code> which will dump the argument to the logger/debug-bar. It works much like <code>var_dump</code>.</p>

<h3 id="logs">Logs</h3>

<p>Dispatch and debug logging goes to the file <code>/log/development.log</code>. Additionally, the starterpack is configured to send php-errors to the file <code>/log/error.log</code>. While the development log is intended to use during development, the error log will usually be used on a production system. The log is configured by the <code>.htaccess</code> file in <code>www</code>. For a production site, you should edit this file to disable display of errors in the browser, and instead rely on the error log.</p>

<h3 id="functional-testing">Functional testing</h3>

<p>Konstrukt comes with a testing harnish for testing components. Since all access to the HTTP layer is encapsulated in adapters, it is possible to test your application down to the HTTP level without actually having a running web server. This is useful for writing automated tests.
The testing harnish consists of an extension to the <a href="http://www.simpletest.org/">SimpleTest</a> unit testing framework. The class <code>k_VirtualSimpleBrowser</code> acts as a drop-in replacement for <a href="http://simpletest.org/api/SimpleTest/WebTester/SimpleBrowser.html"><code>SimpleBrowser</code></a>. To use it in a testcase, write your <code>WebTestCase</code> as normal, but override the method <code>createBrowser()</code> as this:</p>

<pre class="php"><span class="kw2">class</span> TestOfMyComponent <span class="kw2">extends</span> WebTestCase <span class="br0">&#123;</span>
  <span class="kw2">function</span> createBrowser<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw1">return</span> <span class="kw2">new</span> k_VirtualSimpleBrowser<span class="br0">&#40;</span><span class="st0">'components_MyComponent'</span><span class="br0">&#41;</span>;
  <span class="br0">&#125;</span>
  <span class="kw2">function</span> test_request_root<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="re0">$this</span>-&gt;<span class="me1">assertTrue</span><span class="br0">&#40;</span><span class="re0">$this</span>-&gt;<span class="me1">get</span><span class="br0">&#40;</span><span class="st0">'/'</span><span class="br0">&#41;</span><span class="br0">&#41;</span>;
    <span class="re0">$this</span>-&gt;<span class="me1">assertResponse</span><span class="br0">&#40;</span><span class="nu0">200</span><span class="br0">&#41;</span>;
  <span class="br0">&#125;</span>
<span class="br0">&#125;</span>
&nbsp;</pre>
</body>
</html>
